package com.sunlg.smarthome.utils;

import android.util.Log;

import com.sunlg.smarthome.data.weather.City;
import com.sunlg.smarthome.data.weather.Weather;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by sunlg on 2017/5/27.
 */

public class JsonUtils {
    private static final String TAG = JsonUtils.class.getName();

    /**
     * 实况天气解析函数
     * @param weatherJsonStr
     * @return
     */
    public static Weather weatherJsonStr2Weather(String weatherJsonStr){
        Weather weather = null;
        try {
            //解析json数据
            JSONObject jsonObject = new JSONObject(weatherJsonStr);
            JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5");
            JSONObject weatherObject = jsonArray.getJSONObject(0);
            if (weatherObject.getString("status").equals("ok")) {
                weather = new Weather();
                JSONObject basic = weatherObject.getJSONObject("basic");
                JSONObject now = weatherObject.getJSONObject("now");
                JSONObject cond = now.getJSONObject("cond");
                JSONObject wind = now.getJSONObject("wind");
                JSONObject update = basic.getJSONObject("update");

                weather.setCity(basic.getString("city"));
                weather.setDesc(cond.getString("txt"));
                weather.setTime(update.getString("loc"));
                weather.setTmp(now.getString("tmp"));
                weather.setHum(now.getString("hum"));
                weather.setDir(wind.getString("dir"));
                weather.setSc(wind.getString("sc"));
                weather.setPres(now.getString("pres"));
                weather.setFl(now.getString("fl"));
            }
        }catch (JSONException e){
            Log.e(TAG, e.getMessage());
        }
        return weather;
    }

    /**
     * 查询城市解析函数
     * @param cityJsonStr
     * @return
     */
    public static City cityJsonStr2City(String cityJsonStr){
        City city = null;
        try {
            //解析json数据
            JSONObject jsonObject = new JSONObject(cityJsonStr);
            JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5");
            JSONObject weatherObject = jsonArray.getJSONObject(0);
            if (weatherObject.getString("status").equals("ok")) {
                city = new City();
                JSONObject basic = weatherObject.getJSONObject("basic");

                city.setName(basic.getString("city"));
                city.setCode(basic.getString("id"));
                city.setProvince(basic.getString("prov"));
            }
        }catch (JSONException e){
            Log.e(TAG, e.getMessage());
        }
        return city;
    }
}
